import Vue from 'vue'
import { login, getLoginUser } from '@/api/system/loginManage'
import { ACCESS_TOKEN, ALL_MENU, DICT_TYPE_TREE_DATA } from '@/store/mutation-types'

import { welcome } from '@/utils/util'

const user = {
  state: {
    token: '',
    nickname: '',
    username: '',
    welcome: '',
    avatar: '',
    buttons: [], // 按钮权限
    is_superuser: '', // 是否是超管
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { nickname, username, welcome }) => {
      state.nickname = nickname
      state.username = username
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_BUTTONS: (state, buttons) => {
      state.buttons = buttons
    },
    SET_ADMINTYPE: (state, is_superuser) => {
      state.is_superuser = is_superuser
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          if (!response.success) {
            reject(response.message)
            return
          }
          const result = response.data
          Vue.ls.set(ACCESS_TOKEN, result.access, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', result.access)
          resolve()
          // eslint-disable-next-line handle-callback-err
        }).catch(error => {
          // eslint-disable-next-line prefer-promise-reject-errors
          reject('后端未启动或代理错误')
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getLoginUser().then(response => {
          if (response.success) {
            const data = response.data
            commit('SET_ADMINTYPE', data.is_superuser)
            commit('SET_ROLES', 1)
            commit('SET_BUTTONS', data.permissions)
            commit('SET_INFO', data)
            commit('SET_NAME', { nickname: data.nickname, username: data.username, welcome: welcome() })
            // if (data.avatar != null) {
            //   commit('SET_AVATAR', process.env.VUE_APP_API_BASE_URL + '/sysFileInfo/preview?id=' + data.avatar)
            // }
            resolve(data)
          } else {
            // eslint-disable-next-line no-undef
            reject(new Error(response.error))
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout({ commit }) {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_BUTTONS', [])
      commit('SET_ADMINTYPE', '')
      Vue.ls.remove(ACCESS_TOKEN)
      Vue.ls.remove(ALL_MENU)
      Vue.ls.remove(DICT_TYPE_TREE_DATA)
    }

  }
}

export default user
